package pers.cocoadel.springcloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author rwby
 */
@RestController()
@RequestMapping("/payment")
//@DefaultProperties(defaultFallback = "paymentTimeOutGlobalHandler",
//        commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")})
public class PaymentController
{

    @GetMapping("/ok")
    public String getPaymentOK()
    {
        return "线程：" + Thread.currentThread().getName() + "返回成功！o(∩_∩)o 哈哈";
    }

    //    @HystrixCommand(fallbackMethod = "paymentTimeOutHandler",
//            commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")})
//    @HystrixCommand
    @GetMapping("/time_out")
    public String getPaymentTimeOut()
    {
        int timeNumber = 5;
        try
        {
            TimeUnit.SECONDS.sleep(timeNumber);
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        return "线程：" + Thread.currentThread().getName() + "返回成功！o(∩_∩)o 哈哈";

    }

    public String paymentTimeOutHandler()
    {
        return "线程：" + Thread.currentThread().getName() + " 服务器繁忙或者发生错误，返回失败！(┬＿┬)";
    }

    public String paymentTimeOutGlobalHandler()
    {
        return "线程：" + Thread.currentThread().getName() + " global!服务器繁忙或者发生错误，返回失败！(┬＿┬)";
    }

    @HystrixCommand(fallbackMethod ="paymentCircuitBreakerHandler",
    commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")})
    @GetMapping("/cb/{id}")
    public String paymentCircuitBreaker(@PathVariable("id") Integer id)
    {
        if (id > 30)
        {
            throw new IllegalArgumentException("参数错误！");
        }

        return Thread.currentThread().getName() +String.format(" 成功返回O{id:%s} O(∩_∩)",id);
    }

    public String paymentCircuitBreakerHandler(Integer id)
    {
        return Thread.currentThread().getName() + String.format(" 返回失败{id:%s}：服务器繁忙！/(ㄒoㄒ)/~~",id);
    }
}
